package org.everyday;

import java.util.LinkedList;
import java.util.List;

/**
 * @Author: Tang World
 * @Date: 25/8/2022 下午12:25
 */
public class L658 {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> res= new LinkedList<>();
        int l=0,r=arr.length-1;
        if(x<arr[l]){
            while(l<k) {
                res.add(arr[l]);
                l++;
            }
            return res;
        }
        if(x>arr[r]){
            l = r+1-k;
            while(l<=r) {
                res.add(arr[l]);
                l++;
            }
            return res;
        }

        while(r-l+1>k){
            int left = Math.abs(arr[l]-x);
            int right = Math.abs(arr[r]-x);
            if(left<right){
                r--;
            }else if(left>right){
                l++;
            }else{
                r--;
            }
        }

        while(l<=r){
            res.add(arr[l]);
            l++;
        }
        return res;
    }

    public static void main(String[] args) {
        new L658().findClosestElements(new int[]{3,5,8,10},2,15);
    }
}
